package com.py.credit.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.OrgConstant;
import com.py.credit.entity.Account;
import com.py.credit.entity.Element;
import com.py.credit.entity.Organization;
import com.py.credit.entity.Personnel;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.OrgTableFieldEnum;
import com.py.credit.service.OrgService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "org")
@RestController
@RequestMapping(value = "/org")
public class FrontOragnizationController {
	private static final String FRONT_F_TABLE_ID = "forglist";

	@Autowired
	private OrgService orgService;

	@RequestMapping(value = "/front/getFOrgList.json", method = RequestMethod.POST)
	@ApiOperation(value = "前台获取机构列表", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<List<Map<String, Object>>> getFOrgList(
			@ApiParam(required = false, name = "conditions", value = "搜索条件") String condition, Page page,
			HttpServletRequest request) {

		List<Map<String, Object>> orgList = new ArrayList<>();

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		if (account != null) {

			String[] configColumns = (String[]) MapCache.get(account.getId() + "_" + FRONT_F_TABLE_ID);

			List<String> showColumns = (configColumns == null || configColumns.length == 0)
					? OrgTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);

			String[] additionalColumns = { "orgId" };

			orgList = orgService.getOrgListByConditionForPage(account.getOrgId(), showColumns, additionalColumns,
					condition, page);

		} else {
			ExceptionLogger.error("FrontModelController#getFOrgList", "未获取到当前用户信息！");
		}

		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), orgList);

	}

	@ApiOperation(value = "获取高级搜索条件", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/front/getAdvancedConditionColumns.json", method = RequestMethod.GET)
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {

		return new RestServiceResult<List<OptionalColumn>>(OrgTableFieldEnum.getAdvancedConditionColumns());

	}

	@ApiOperation(value = "获取表头列", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/front/getOptionalColums.json", method = RequestMethod.GET)
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {

		return new RestServiceResult<List<OptionalColumn>>(OrgTableFieldEnum.getOptionalColumns());

	}

	@ApiOperation(value = "自定义展示列", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/front/addFColumns.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addColumns(
			@ApiParam(required = true, name = "columns", value = "展示列数组") @RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");

		if (account != null) {

			MapCache.set(account.getId() + "_" + FRONT_F_TABLE_ID, columns);

		} else {

			ExceptionLogger.error("FrontModelController#addFColumns", "未获取到当前用户信息！");

		}

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "导出列表", httpMethod = "GET")
	@RequestMapping("/front/fExport.json")
	public void fExport(
			@ApiParam(required = true, name = "condition", value = "搜索条件") @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@ApiParam(required = true, name = "columnEN", value = "导出列") @RequestParam(value = "columnEN", required = true) String columnEN,
			HttpServletResponse response, HttpServletRequest request, Page page) throws IOException {

		page.setLimit(1000);

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");

		if (account != null) {

			List<String> columns = JSONArray.parseArray(columnEN, String.class);

			List<Map<String, Object>> data = orgService.getOrgListByConditionForPage(account.getOrgId(), columns, null,
					condition, page);

			List<OptionalColumn> optionalColumns = OrgTableFieldEnum.getOptionalColumns();

			ExcelUtil.downloadExcel(response, data, "机构列表", "机构列表", columns, optionalColumns);
		} else {
			ExceptionLogger.error("FrontModelController#fExport", "未获取到当前用户信息！");
		}

	}

	@RequestMapping(value = "/front/grant.json", method = RequestMethod.POST)
	@ApiOperation(value = "分配账号", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<Object> grant(Account ac) {

		ac.setType(OrgConstant.ACCOUNT_TYPE_SECONDARY);

		if (orgService.isAccountExist(ac.getAccount())) {

			throw new ServiceException("账号已存在");

		}
		orgService.addAcccount(ac);

		return new RestServiceResult<Object>();

	}

	@RequestMapping(value = "/front/getICardFPic.png", method = RequestMethod.GET)
	@ApiOperation(value = "获取身份证正图片", httpMethod = "GET", produces = "image/*")
	public void getICardFPic(
			@ApiParam(required = true, name = "id", value = "人员编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Personnel personnel = orgService.getPersonnelById(id);

		byte[] data = orgService.getPic(personnel.getIdCardFPic());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/front/getICardBPic.png", method = RequestMethod.GET)
	@ApiOperation(value = "获取身份证反面图片", httpMethod = "GET", produces = "image/*")
	public void getICardBPic(
			@ApiParam(required = true, name = "id", value = "人员编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Personnel personnel = orgService.getPersonnelById(id);

		byte[] data = orgService.getPic(personnel.getIdCardBPic());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/front/getCertificate.png", method = RequestMethod.GET)
	@ApiOperation(value = "获取资质证书", httpMethod = "GET", produces = "image/*")
	public void getCertificate(
			@ApiParam(required = true, name = "id", value = "人员编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Personnel personnel = orgService.getPersonnelById(id);

		byte[] data = orgService.getPic(personnel.getCertification());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/front/getAccountCertificate.png", method = RequestMethod.GET)
	@ApiOperation(value = "银行开户证明", httpMethod = "GET", produces = "image/*")
	public void getAccountCertificate(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getAccountCertificate());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/front/getBusinessLicence.png", method = RequestMethod.GET)
	@ApiOperation(value = "营业执照", httpMethod = "GET", produces = "image/*")
	public void getBusinessLicence(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getBusinessLicence());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/front/getCommitmentLetter.png", method = RequestMethod.GET)
	@ApiOperation(value = "信用承诺书", httpMethod = "GET", produces = "image/*")
	public void getCommitmentLetter(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getCommitmentLetter());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/front/getOrgCodeCertificate.png", method = RequestMethod.GET)
	@ApiOperation(value = "组织机构代码证", httpMethod = "GET", produces = "image/*")
	public void getOrgCodeCertificate(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getOrgCodeCertificate());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/front/getOrgCrSample.png", method = RequestMethod.GET)
	@ApiOperation(value = "企业信用评价样本", httpMethod = "GET", produces = "image/*")
	public void getOrgCrSample(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getOrgCrSample());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/front/getTaxRegisterLicence.png", method = RequestMethod.GET)
	@ApiOperation(value = "获取税务登记证", httpMethod = "GET", produces = "image/*")
	public void getTaxRegisterLicence(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getTaxRegisterLicence());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/front/getRegulator.png", method = RequestMethod.GET)
	@ApiOperation(value = "制度标准", httpMethod = "GET", produces = "image/*")
	public void getRegulator(
			@ApiParam(required = true, name = "id", value = "组织编号") @RequestParam(required = true) String id,
			HttpServletResponse response) throws Exception {

		Organization org = orgService.getOrgById(id);

		byte[] data = orgService.getPic(org.getRegulator());

		IOUtils.write(data, response.getOutputStream());

	}

	@ApiOperation(value = "获取后台logo", httpMethod = "GET", produces = "image/*")
	@RequestMapping(value = "/front/getSysLogo.png", method = RequestMethod.GET)
	public void getSysLogo(
			@ApiParam(name = "orgId", value = "关联机构编号", required = true) @RequestParam(required = true) String orgId,
			HttpServletResponse response) throws Exception {

		Element element = orgService.getElement(orgId);

		byte[] data = orgService.getPic(element.getSysLogo());

		IOUtils.write(data, response.getOutputStream());

	}

	@ApiOperation(value = "獲取后台logo缩放", httpMethod = "GET", produces = "image/*")
	@RequestMapping(value = "/front/getScalingSysLogo.png", method = RequestMethod.GET)
	public void getScalingSysLogo(
			@ApiParam(name = "orgId", value = "关联机构编号", required = true) @RequestParam(required = true) String orgId,
			HttpServletResponse response) throws Exception {

		Element element = orgService.getElement(orgId);

		byte[] data = orgService.getPic(element.getScalingSysLogo());

		IOUtils.write(data, response.getOutputStream());

	}

	@RequestMapping(value = "/front/getProfessionals.json", method = RequestMethod.GET)
	@ApiOperation(value = "获取专业人员", httpMethod = "GET", produces = "application/json")
	public RestServiceResult<List<Personnel>> getProfessionals(
			@ApiParam(required = true, name = "orgId", value = "关联机构编号") @RequestParam(required = true) String orgId) {

		List<Personnel> professionals = orgService.getPersonnels(orgId, OrgConstant.PERSONNEL_TYPE_PROFESSIONAL);
		return new RestServiceResult<List<Personnel>>(professionals);

	}

	@RequestMapping(value = "/front/getOrgDetail.json", method = RequestMethod.GET)
	@ApiOperation(value = "获取组织详情", httpMethod = "GET", produces = "application/json")
	public RestServiceResult<Object> getOrgDetail(
			@ApiParam(required = true, name = "orgId", value = "关联机构编号") @RequestParam(required = true) String orgId) {

		Map<String, Object> result = orgService.getDetail(orgId);

		return new RestServiceResult<Object>(result);

	}

}
